import ContentLayout from '@/layouts/ContentLayout'
import ArrayUtils from '@/utils/ArrayUtils'
import { PROD_STATUS } from '@/consts/project'
import { Button, Space, Table, Modal, Form, Input, DatePicker, message, Tag } from 'antd'
import { useState, useEffect } from 'react'
import styles from './style.less'
import ActionDropdown from '@/components/ActionDropdown';
import { connect, history } from 'umi';
import EnterpriseUserSelect from '@/components/EnterpriseUserSelect';
import UserBrief from '@/components/UserBrief'
import { formetDate, formetTime_MDHm } from '@/utils/dateUtils'
import { pageProd, save } from '@/services/project/prod'
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
import CheckActon from '../../CheckActoin'


export const ProdStatus = (props) => {
    const {
        status
    } = props

    if (status || status === 0) {
        return <Tag color={PROD_STATUS[status]?.color}>{PROD_STATUS[status]?.name}</Tag>
    }
    return (
        <Tag>/</Tag>
    )
}

const ProdPage = (props) => {
    const {
        projectId,
        routeParam,
        onQueryParamChange,
        queryInitParams = {},
        projectPermission
    } = props

    const [params, setParams] = useState({
        pageNum: 1,
        pageSize: 10
    })
    const [showAddProdModalVisiable, setShowAddProdModalVisiable] = useState(false)
    const [showMe, setShowMe] = useState(false)
    const [form] = Form.useForm();
    const [prodPage, setProdPage] = useState()
    const [prodPageLoading, setProdPageLoading] = useState()
    const [permission, setPermission] = useState({})

    useEffect(() => {
        let initParams = {
            ...params,
            ...queryInitParams,
        };
        setParams(initParams)
        if (projectId) {
            queryProdPage(initParams)
        }
    }, [projectId])

    useEffect(() => {
        setPermission({
            ...projectPermission?.prod
        })
    }, [projectPermission])



    const onParamChange = (param, doQuery) => {
        if (param && !param.pageNum) {
            param.pageNum = 1;
        }
        let newParams = { ...params, ...param }
        setParams(newParams)
        if (onQueryParamChange) {
            onQueryParamChange(newParams)
        }
        if (doQuery) {
            queryProdPage(newParams)
        }
    }

    const queryProdPage = (queryParams) => {
        // console.log(queryParams)
        setProdPageLoading(true)
        pageProd(projectId, (queryParams || params))
            .then(({ data }) => {
                setProdPage(data)
                setProdPageLoading(false)
            })
    }

    const showProdDetail = (prod) => {
        history.push(`/projects/${projectId}/prod/${prod.id}`)
    }

    const saveProd = async () => {
        const values = await form.validateFields()
        console.log(values)
        const data = {
            ...values
        }
        if (values.planDate) {
            data.planStartDate = formetDate(values.planDate[0]);
            data.planEndDate = formetDate(values.planDate[1]);
            data.planDate = undefined
        }
        if (values.actualDate) {
            data.actualStartDate = formetDate(values.actualDate[0]);
            data.actualEndDate = formetDate(values.actualDate[1]);
            data.actualDate = undefined
        }
        save(projectId, data).then(({ success }) => {
            if (success) {
                message.success("保存成功！")
                queryProdPage();
                setShowAddProdModalVisiable(false);
                form.resetFields();
            }
        })
    }

    const queryItems = [

        {
            name: "inStatus",
            label: "状态",
            isMain: true,
            type: "tagSelect",
            options: ArrayUtils.jsonToArray(PROD_STATUS).map((item) => ({
                value: item.key,
                label: item.value.name
            }))
        },
        {
            name: "likeName",
            label: "名称",
            isMain: true,
            span: 8,
            type: "input",
        },
        {
            name: "inUserId",
            label: "负责人",
            isMain: true,
            span: 8,
            type: "userSelect",
        },
        {
            name: "likeVersion",
            label: "版本号",
            isMain: true,
            span: 8,
            type: "input",
        },
    ]

    const actionHeader = [
        <ActionDropdown
            key="actions"
            status={params?.isArchived && "filter"}
            placement="bottomRight"
            actions={[
                <CheckActon
                    check={params?.isArchived === 1}
                    onChange={(value) => {
                        if (value) {
                            onParamChange({
                                isArchived: 1
                            }, true)
                        } else {
                            onParamChange({
                                isArchived: null
                            }, true)
                        }
                    }}
                    label={'查看归档数据'}
                />,
            ]}
        />,
        <Button type="primary" size="middle" onClick={() => {
            setShowAddProdModalVisiable(true)
        }}>
            新增
        </Button>,
        ,
        <CheckActon
            check={params?.mySelection === 1}
            onChange={(value) => {
                if (value) {
                    onParamChange({
                        mySelection: 1
                    }, true)
                } else {
                    onParamChange({
                        mySelection: null
                    }, true)
                }
            }}
            label={'只看我的'}
        />
    ]

    const tableColumns = [
        {
            title: '项目名',
            dataIndex: 'name',
            key: 'name',
            width: "20%",
            fixed: 'left',
            ellipsis: {
                showTitle: true
            },
            sorter: (a, b) => a.name.localeCompare(b.name),
        },
        {
            title: '版本',
            dataIndex: 'version',
            key: 'version',
            width: "10%",
            sorter: (a, b) => a.version.localeCompare(b.version),
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: "10%",
            sorter: (a, b) => a.status - b.status,
            render: (text, record) => <ProdStatus status={record.status}></ProdStatus>
        },
        {
            title: '负责人',
            dataIndex: 'userId',
            key: 'userId',
            width: "14%",
            render: (text, record) => <UserBrief user={record.user}></UserBrief>,
        },
        {
            title: '排期',
            dataIndex: 'date',
            key: 'date',
            width: "200px",
            ellipsis: {
                showTitle: true
            },
            render: (text, record) => record.actualStartDate ? (`${formetDate(record.actualStartDate)}~${formetDate(record.actualEndDate)}`)
                : (`${formetDate(record.planStartDate)}~${formetDate(record.planStartDate)}`),
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            sorter: (a, b) => a.createTime.localeCompare(b.createTime),
            render: (text, record) => formetTime_MDHm(record.createTime),
            defaultSortOrder: 'descend'
        }
    ]

    const filterColumn = (tableColumns) => {
        // if (tableColumns) {
        //     return tableColumns.filter(column => column.key === 'name'
        //         || column.key === 'status'
        //     )
        // }
        return tableColumns;
    }

    return <>
        <ContentLayout
            queryItems={queryItems}
            actionHeader={actionHeader}
            queryInitParams={queryInitParams}
            onQueryChange={onParamChange}
            content={
                <Table
                    onChange={(pagination, filters, sorter) => {
                        console.log(pagination, sorter)
                        onParamChange({
                            pageNum: pagination.pageSize === params.pageSize ? pagination.current : 1,
                            pageSize: pagination.pageSize
                        }, true)
                    }}
                    columns={filterColumn(tableColumns)}
                    rowKey="id"
                    loading={prodPageLoading}
                    dataSource={prodPage && prodPage.list}
                    pagination={{
                        position: ["bottomCenter"],
                        showSizeChanger: true,
                        pageSize: params.pageSize || 10,
                        total: prodPage && prodPage.count,
                        current: prodPage && prodPage.pageNum,
                        pageSizeOptions: [10, 20, 50],
                        showTotal: (total, range) => `总数： ${total} `
                    }}
                    size="small"
                    onRow={record => {
                        return {
                            onClick: () => {
                                showProdDetail(record)
                            }
                        }
                    }}
                >
                </Table>
            }
        />
        <Modal
            visible={showAddProdModalVisiable}
            closable
            title={"新增需求"}
            onCancel={() => {
                setShowAddProdModalVisiable(false)
            }}
            onOk={() => {
                saveProd();
            }}
            destroyOnClose
            okText={"确认"}
            cancelText={"取消"}
        >
            <Form
                form={form}
                labelAlign="right"
                labelCol={{ span: 4 }}
            >
                <FormItem
                    label={"名称"}
                    name="name"
                    rules={[
                        {
                            required: true,
                            message: "请输入名称",
                        },
                    ]}
                >
                    <Input placeholder={"请输入名称"} maxLength={20} ></Input>
                </FormItem>
                <FormItem
                    label={"版本号"}
                    name="version"
                    rules={[
                        {
                            required: true,
                            message: "请输入版本号",
                        },
                    ]}
                >
                    <Input placeholder={"请输入版本号"} maxLength={20} ></Input>
                </FormItem>
                <FormItem
                    label={"负责人"}
                    name="userId"
                    rules={[
                        {
                            required: true,
                            message: "请选择负责人",
                        },
                    ]}
                >
                    <EnterpriseUserSelect projectId={projectId} ></EnterpriseUserSelect>
                </FormItem>
                <Form.Item name="actualDate" label={"实际周期"}>
                    <RangePicker format="YYYY-MM-DD" />
                </Form.Item>
                <Form.Item name="planDate" label={"预计周期"}>
                    <RangePicker format="YYYY-MM-DD" />
                </Form.Item>
                <FormItem label={"描述"}
                    name="description"
                    rules={[
                        {
                            required: true,
                            message: "请输入描述",
                        },
                    ]}
                >
                    <Input.TextArea placeholder="请输入描述" maxLength={200} showCount>
                    </Input.TextArea>
                </FormItem>
            </Form>
        </Modal>
    </>
}


export default connect(({ }) => ({

}))(ProdPage);